package com.ll.gulimall.test.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token) {

        if (token != null) {
            //查询用户 使用http发送
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://ssoserver.com:8080/info?token=" + token, String.class);
            String user = responseEntity.getBody();
            //将Token存入Session
            session.setAttribute("loginUser",user);

        }
        if (session.getAttribute("loginUser") == null) {
            //未登录   跳转登录服务器
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client1.com:8088/employees";
        } else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("王五");
            model.addAttribute("emps", emps);
            return "list";
        }

    }
}